package controller;

import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

import service.GetContent;

@SuppressWarnings("serial")
public class CheckKeywordServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setCharacterEncoding("utf-8");
		String domain = req.getParameter("domain");
		String q = req.getParameter("q");
		String type = req.getParameter("type");
		
		if(domain!=null&&q!=null)
		{
			q=URLDecoder.decode(q,"UTF-8").replaceAll("[ ]+", "+");
			ArrayList<Future> arFuture = new ArrayList<Future>();
			URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
			
			for (int i = 0; i < 10; i++) {
				URL url = new URL("https://"+type+"/search?sclient=psy-ab&site=&source=hp&q="+q+"&btnG=T%C3%ACm+ki%E1%BA%BFm&start="+i*10);			
				
				arFuture.add(fetcher.fetchAsync(url));
			}
			
			String table = "<table width='100%'>";
			table += "<tr><td><strong>Url</strong></td><td align='center'><strong>Order</strong><td align='center'><strong>Page</strong></td></td></tr>";
			for (int i = 0; i < arFuture.size(); i++) {
				
				String[] arr = new GetContent().Get(arFuture.get(i),i,domain).split("\\|"); 
				if(arr.length==3)
				{
					table += "<tr><td><a href='"+arr[0]+"'>"+Utils.fomatUrl(arr[0])+"</a></td>"+"<td align='center'>"+(Integer.parseInt(arr[2])+1)+"</td>"+"<td align='center'>"+(Integer.parseInt(arr[1])+1)+"</td></tr>";
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			table += "</table>";
			
			req.setAttribute("table", table);
			req.setAttribute("domain", domain);
			req.setAttribute("q", q);
			req.setAttribute("type", type);
		}
		try {
			req.getRequestDispatcher("check-keyword.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
